import { getContext } from '@/context/common/applicationContext'
import React, { Component } from 'react'
import { Col, Row, Statistic, Tag, Card, Collapse, Table, Spin } from 'antd'
import {
    CheckCircleOutlined,
    ClockCircleOutlined,
    SyncOutlined
} from '@ant-design/icons'
import { commonQueryByCode } from '@/service/document/documentService'
import paramUtil from '@/utils/paramUtil'
import { Link } from 'react-router-dom'

class CrawlHome extends Component {

    state = {
        loading: true,
        crawlTaskStatus: null,
        crawlTaskType: null,
        taskId: null, //定时任务id
        statisticInfo: {}, //任务基本统计信息
        taskList: []
    }

    //最大服务数、运行中服务数、等待服务数、完成服务数
    async componentDidMount() {
        //获取参数
        let crawlTaskStatus = await paramUtil.get('crawlTaskStatus')
        let crawlTaskType = await paramUtil.get('crawlTaskType')

        await this.getTaskServiceBasicInfo()
        let taskId = setInterval(this.getTaskServiceBasicInfo, 60000)
        await new Promise(resolve => {
            this.setState({
                crawlTaskStatus,
                crawlTaskType,
                taskId,
                loading: false
            }, resolve)
        })
    }

    async componentWillUnmount() {
        if (this.state.taskId) {
            clearInterval(this.state.taskId)
        }
    }

    //获取爬取平台基本服务信息
    getTaskServiceBasicInfo = async () => {
        let statisticInfo = {}
        let taskList = []
        //获取统计信息
        const response1 = commonQueryByCode({ commandCode: 'datatCrawlParams' })
        //获取列表信息
        const response2 = commonQueryByCode({ commandCode: 'getTaskInfoOfNoEnd' })
        const responses = await Promise.all([response1, response2])
        if (responses[0] && responses[0].code === 200) {
            statisticInfo = responses[0].data.documents[0].content
        }
        if (responses[1] && responses[1].code === 200) {
            responses[1].data.documents.forEach(item => {
                taskList.push(item.content)
            })
        }
        //获取任务列表（RUNNING、WAITING）
        await new Promise(resolve => {
            this.setState({
                statisticInfo,
                taskList,
            }, resolve)
        })
    }

    //任务基本信息统计
    renderBasicStatistic = () => {
        const { statisticInfo } = this.state
        return (
            <Row gutter={16}>
                <Col span={6}>
                    <Card bordered={true}>
                        <Statistic title='最大同时任务数' value={statisticInfo.maxTaskNumber || 0} />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card bordered={true}>
                        <Statistic title='已完成任务数' value={statisticInfo.endTask || 0} suffix={<Tag icon={<CheckCircleOutlined />} color='success'>success</Tag>} />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card bordered={true}>
                        <Statistic title='进行中任务数' value={statisticInfo.runningTask || 0} suffix={<Tag icon={<SyncOutlined spin />} color='processing'>running</Tag>} />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card bordered={true}>
                        <Statistic title='等待中任务数' value={statisticInfo.waitingTask || 0} suffix={<Tag icon={<ClockCircleOutlined />} color='warning'>waiting</Tag>} />
                    </Card>
                </Col>
            </Row>
        )
    }

    //进行中任务列表
    renderTaskList = () => {
        const columns = [
            {
                title: '服务类型', dataIndex: 'taskType', render: (text) => {
                    const type = (this.state.crawlTaskType.children || []).find(item => item.code === text)
                    if (type) return type.content
                    else return text
                }
            },
            {
                title: '服务名称', dataIndex: 'taskName', render: (text, record) => {
                    if (this.props.user.id === record.createUser) return <Link to={`/jms/crawl/${record.taskType}?taskName=${record.taskName}`}>{text}</Link>
                    else return text
                }
            },
            {
                title: '爬取关键词', dataIndex: 'importantCode', render: (text) => {
                    let codes = JSON.parse(text)
                    return codes.join(',')
                }
            },
            { title: '创建时间', dataIndex: 'createTime', sorter: (a, b) => a.createTime > b.createTime ? 1 : -1 },
            { title: '创建者', dataIndex: 'nickname' },
            {
                title: '服务状态', dataIndex: 'taskStatus', render: (text) => {
                    switch (text) {
                        case 'RUNNING':
                            return <Tag color='geekblue'>运行中</Tag>
                        case 'WAITING':
                            return <Tag color='volcano'>等待中</Tag>
                        default:
                            return text
                    }
                }
            },
        ]
        return <Table columns={columns} dataSource={this.state.taskList} rowKey='id' pagination={false} />
    }

    //等待任务列表

    render() {
        if (this.state.loading === true) return <Spin />
        let collapseItems = [
            {
                key: '1',
                label: '任务基本信息统计',
                children: this.renderBasicStatistic()
            },
            {
                key: '2',
                label: '任务详情',
                children: this.renderTaskList()
            }
        ]
        return (
            <Collapse
                defaultActiveKey={['1', '2']}
                ghost
                items={collapseItems}
            />
        )
    }
}

export default getContext(CrawlHome)
